package cn.coderpig.cpfastaccessibility

import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.core.widget.doAfterTextChanged
import androidx.core.widget.doOnTextChanged
import androidx.recyclerview.widget.RecyclerView
import cn.coderpig.cp_fast_accessibility.NodeWrapper
import cn.coderpig.cp_fast_accessibility.isAccessibilityEnable
import cn.coderpig.cp_fast_accessibility.requireAccessibility
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.annotation.JSONField
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.anim.DefaultAnimator
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.enums.SidePattern


class MainActivity : AppCompatActivity() {
    private lateinit var mServiceStatusTv: TextView

    //    private lateinit var mOpenTargetAppBt: Button
    private lateinit var texts: MutableList<Item>
    private lateinit var mSimpleAdapter: SimpleAdapter
    private val mClickListener = View.OnClickListener {
        when (it.id) {
            R.id.tv_service_status -> {
                if (isAccessibilityEnable) shortToast(getStringRes(R.string.service_is_enable_tips))
                else requireAccessibility()
            }

            R.id.button_add -> {
                showEditDialog()
            }

//            R.id.bt_open_target_app -> startApp("com.sankuai.meituan", "com.meituan.android.pt.homepage.activity.MainActivity", "未安装美团")
//            R.id.bt_open_target_app -> startApp("com.tencent.mm", "com.tencent.mm.ui.LauncherUI", "未安装微信")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        // adb shell "dumpsys window | grep mCurrentFocus" 获取当前焦点activity
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        if (!Settings.canDrawOverlays(this)) {
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            startActivity(intent)
        }
        requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 1)
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val isNotificationEnabled = notificationManager.areNotificationsEnabled()
        if (!isNotificationEnabled) {
            val intent = Intent()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS")
                intent.putExtra("app_package", packageName)
                intent.putExtra("app_uid", applicationInfo.uid)
            } else {
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.addCategory(Intent.CATEGORY_DEFAULT)
                intent.setData(Uri.parse("package:$packageName"))
            }
            startActivity(intent)
        }
    }

    private fun initView() {
        mServiceStatusTv = findViewById(R.id.tv_service_status)
//        mOpenTargetAppBt = findViewById(R.id.bt_open_target_app)
        mServiceStatusTv.setOnClickListener(mClickListener)
        val buttonAdd = findViewById<View>(R.id.button_add)
        buttonAdd.setOnClickListener(mClickListener)
//        mOpenTargetAppBt.setOnClickListener(mClickListener)

        findViewById<EditText>(R.id.tv_sx_centent).doAfterTextChanged {
            it?.let {
                MyApp.sp.edit(true) {
                    putString("sx_centent", it.toString())
                }
            }
        }

        val rvText = findViewById<RecyclerView>(R.id.rvText)
        texts = JSON.parseArray(MyApp.sp.getString("texts", "[]"), Item::class.java)

        mSimpleAdapter = SimpleAdapter(texts) { item ->
            Toast.makeText(this, "Clicked: ${item.text}", Toast.LENGTH_SHORT).show()
        }
        rvText.adapter = mSimpleAdapter
        rvText.layoutManager = FullyFlexboxLayoutManager(this).apply {
            flexDirection = FlexDirection.ROW
            flexWrap = FlexWrap.WRAP
            alignItems = AlignItems.STRETCH
        }
    }

    // 显示编辑对话框
    private fun showEditDialog() {
        // 创建自定义对话框视图
        val dialogView: View = LayoutInflater.from(this).inflate(R.layout.dialog_edit, null)
        val editText = dialogView.findViewById<EditText>(R.id.editText)

        // 创建对话框
        val dialog: AlertDialog = AlertDialog.Builder(this)
            .setTitle("输入关键字")
            .setView(dialogView)
            .setPositiveButton("确认") { d, which ->
                val newText = editText.text.toString().trim { it <= ' ' }
                if (newText.isNotEmpty()) {
                    texts.add(Item().apply { text = newText })
                    mSimpleAdapter.notifyDataSetChanged()
                    Toast.makeText(this, "已新增", Toast.LENGTH_SHORT).show()
                    MyApp.sp.edit(true) {
                        putString("texts", JSON.toJSONString(texts))
                    }
                } else {
                    Toast.makeText(this, "输入不能为空", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .create()

        dialog.show()
    }

    override fun onResume() {
        super.onResume()
        if (isAccessibilityEnable) {
            mServiceStatusTv.text = getStringRes(R.string.service_status_enable)
//            mOpenTargetAppBt.visibility = View.VISIBLE
        } else {
            mServiceStatusTv.text = getStringRes(R.string.service_status_disable)
//            mOpenTargetAppBt.visibility = View.GONE
        };
    }

    class Item {
        var text: String = ""
    }

    inner class SimpleAdapter(
        private val items: MutableList<Item>,
        private val onClick: (Item) -> Unit
    ) : RecyclerView.Adapter<SimpleAdapter.ViewHolder>() {

        // 创建 ViewHolder
        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val textView: TextView = view.findViewById(R.id.tvText)

            init {
                view.setOnClickListener { onClick(items[adapterPosition]) }
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.textView.text = items[position].text
            holder.textView.setOnLongClickListener {
                AlertDialog.Builder(holder.textView.context)
                    .setTitle("确认操作")
                    .setMessage("您确定要删除吗？")
                    .setPositiveButton("确定") { dialog, which ->
                        items.removeAt(position)
                        notifyDataSetChanged()
                        Toast.makeText(holder.textView.context, "已删除", Toast.LENGTH_SHORT).show()
                        MyApp.sp.edit(true) {
                            putString("texts", JSON.toJSONString(texts))
                        }
                    }
                    .setNegativeButton("取消", null)
                    .show()
                true
            }
        }

        override fun getItemCount() = items.size
    }
}

class DyUser {
    @JSONField(serialize = false, deserialize = false)
    var avatarNode: NodeWrapper? = null
    var avatar: String? = null
    var title: String? = null
    var content: String? = null
}
